# app.py

from flask import Flask, render_template, request, redirect, url_for
import db_utils

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'

@app.route('/')
def home():
    """显示药品库存信息的主页

    Returns:
        HTML页面: 包含药品库存信息
    """
    connection = db_utils.get_db_connection()
    cursor = connection.cursor()
    cursor.execute('SELECT drug_id, name, total_quantity FROM drug_info')
    drugs = cursor.fetchall()
    cursor.close()
    connection.close()
    return render_template('index.html', drugs=drugs)

@app.route('/add', methods=['GET'])
def show_add_drug_form():
    """显示药品入库的表单页面

    Returns:
        HTML页面: 显示药品入库表单
    """
    return render_template('add_drug.html')

@app.route('/add', methods=['POST'])
def add_drug():
    """处理药品入库请求，更新数据库，并重定向至首页

    Args:
        form_data: 入库表单的数据
    """
    name = request.form['name']
    quantity = int(request.form['quantity'])
    supplier = request.form['supplier']
    purchase_date = request.form['purchase_date']
    db_utils.add_drug(name, quantity, supplier, purchase_date)
    return redirect(url_for('home'))

@app.route('/remove', methods=['GET'])
def show_remove_drug_form():
    """显示药品出库的表单页面

    Returns:
        HTML页面: 显示药品出库表单
    """
    connection = db_utils.get_db_connection()
    cursor = connection.cursor()
    cursor.execute('SELECT drug_id, name FROM drug_info')
    drugs = cursor.fetchall()
    cursor.close()
    connection.close()
    return render_template('remove_drug.html', drugs=drugs)

@app.route('/remove', methods=['POST'])
def remove_drug():
    """处理药品出库请求，更新数据库，并重定向至首页

    Args:
        form_data: 出库表单的数据
    """
    drug_id = int(request.form['drug_id'])
    quantity = int(request.form['quantity'])
    department = request.form['department']
    person = request.form['person']
    usage_date = request.form['usage_date']
    db_utils.remove_drug(drug_id, quantity, department, person, usage_date)
    return redirect(url_for('home'))

@app.route('/check_inventory')
def check_inventory():
    """定时任务或者手动触发的库存检查，低于警戒线时提醒管理人员
    """
    low_stock_items = db_utils.check_low_stock()
    if low_stock_items:
        alert_message = "以下药品库存低于警戒线：\n"
        for item in low_stock_items:
            alert_message += f"药品名称: {item[0]}, 剩余库存: {item[1]}\n"
        print(alert_message)  # 可以替换为发送邮件或其他提醒机制
    return redirect(url_for('home'))

if __name__ == '__main__':
    app.run(debug=True)
